import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.ArrayList;

public class SnakeZero extends Snake
{
    private ArrayList<BodyZero> bodyZero;
    public SnakeZero(World _myWorld)
    {
        super(_myWorld);
        bodyZero = new ArrayList<BodyZero>();
    }
    public void act()
    {
        checkKeydown();
        move();
        updateBody();
        checkFood();
        checkEdge();
        checkGameOver();
        
        checkTime();
    }
    //检测键盘按键事件，若按下方向键，则分别控制贪食蛇朝相应方向移动
    public void checkKeydown(){
        if(Greenfoot.isKeyDown("up")&&direction!=SOUTH){
            direction=NORTH;
        }
        else  if(Greenfoot.isKeyDown("down")&&direction!=NORTH){
            direction=SOUTH;
        }
        else  if(Greenfoot.isKeyDown("left")&&direction!=EAST){
            direction=WEST;
        }
        else  if(Greenfoot.isKeyDown("right")&&direction!=WEST){
            direction=EAST;
        }

    }
    //更新贪食蛇身体
    public void updateBody(){
        if (length > 1) {
            if(bodyZero.size()==length){
                bodyZero.remove(0);     //从蛇身列表中移除蛇尾对应的Body对象
            }
            World w=getWorld();
            w.removeObjects(w.getObjects(BodyZero.class));  //将蛇身从游戏世界中移除
            for(BodyZero b:bodyZero){      //根据蛇身各部分的位置重新添加至游戏世界
                w.addObject(b, b.getLocX(),b.getLocY());
            }
            bodyZero.add(new BodyZero(getX(),getY()));  //将蛇头对应的Body对象添加至蛇身列表
        }
    }
    public void checkGameOver(){
        if(isTouching(Body.class)||isTouching(Food3.class)){  
            TwoPlayerWorld TwoPlayerWorld = (TwoPlayerWorld)getWorld();
            Greenfoot.setWorld(new GameOverMenu("玩家零",TwoPlayerWorld.snakeZero.getLength()-1,TwoPlayerWorld.snakeOne.getLength()-1));
        }
    }
}
